package cn.com.swu.mianyangapp.net;

import com.google.gson.Gson;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

import java.io.IOException;
import java.util.Map;

public class TodoNetRepository {
    private NetService netService;
    private Retrofit retrofit;

    public TodoNetRepository() {
        this.retrofit = TodoNetClient.getRetrofit();
        this.netService = this.retrofit.create(NetService.class);
    }

    public Call<ResponseBody> getCall(String url) {
        return netService.getCall(url);
    }

    public String get(String url) throws IOException {
        Call<ResponseBody> call = netService.getCall(url);
        Response<ResponseBody> response = call.execute();
        String bodyStr = response.body().string();
        return bodyStr;
    }

    public String postStringFromFormData(String url, Map<String, String> map) throws IOException {
        Call<ResponseBody> call = netService.postFormDataCall(url, map);
        Response<ResponseBody> response =  call.execute();
        return response.body().string();
    }

    public Call<ResponseBody> postStringFromFormDataCall(String url, Map<String, String> map) throws IOException {
        return netService.postFormDataCall(url, map);
    }

    public String postFromJson(String url, Map<String, String> map) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), new Gson().toJson(map));
        Call<ResponseBody> call =  netService.postFromJsonCall(url, body);
        Response<ResponseBody> response =  call.execute();
        return response.body().string();
    }

    public Call<ResponseBody> postFromJsonCall(String url, Map<String, String> map) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), new Gson().toJson(map));
        return netService.postFromJsonCall(url, body);
    }

    public Call<ResponseBody> postJsonStrFromJsonCall(String url, String json_str) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json_str);
        return netService.postFromJsonCall(url, body);
    }
}
